package com.softcits.email.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.softcits.email.controller.EmailController;
import com.softcits.email.model.LoginUser;
import com.softcits.email.service.UserService;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    private final static Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class);


    @Autowired
    private PasswordEncoder encoder;
    
    @Autowired
    private UserService userService;
    
    @Override
    public UserDetails loadUserByUsername(String json) throws UsernameNotFoundException {
        LoginUser loginUser = JSON.parseObject(json, LoginUser.class);
        
        if(loginUser == null || "".equals(loginUser.getLoginName()) || "".equals(loginUser.getUserPassword())) {
            LOGGER.warn("The Given parameters are invalid.");
            return null;
        }
        
        SoftCitsUser user = this.userService.getUserByLoginName(loginUser.getLoginName());
        
        if(user == null || user.getUsername() == null || user.getPassword() == null) {
            LOGGER.warn("Access Denied.");
            return null;
        }
        
        if(loginUser.getUserPassword().equals(user.getPassword())) {
            user.setUserPassword(encoder.encode(loginUser.getUserPassword()));
        }
        user.setRemember(loginUser.getRemember());
        
        LOGGER.debug("Welcome to Email System!");
        return user;
    }

}
